﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LeadChina.AssemblyLine.Common
{
    public class ClassVarEvent<T>
    {
        /// <summary>
        /// 存储最新值
        /// </summary>
        private T myValue;
        /// <summary>
        /// 存储最后变化时间
        /// </summary>
        private DateTime _lastUpdateTime;
        public DateTime LastUpdateTime { get => _lastUpdateTime; }
        /// <summary>
        /// 存储最后变化至现在的时间间隔
        /// </summary>
        public int TimeInterval => GetTimeInterval();

        public delegate void MyValueChanged(object sender, EventArgs e);

        public event MyValueChanged OnMyValueChanged;

        public T MyValue
        {
            get { return myValue; }
            set
            {
                //IStructuralEquatable a = (Array)Convert.ChangeType(value, typeof(T));
                if (!Compare(value, myValue))
                {
                    myValue = value;
                    WhenMyValueChange();
                }

            }
        }
        /// <summary>
        /// 对比数据是否改变
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        private bool Compare(T x, T y)
        {
            return EqualityComparer<T>.Default.Equals(x, y);
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        public ClassVarEvent()
        {
            _lastUpdateTime = DateTime.Now;
            myValue = default(T);
        }
        /// <summary>
        /// 更改之后 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AfterMyValueChanged(object sender, EventArgs e)
        {
        }
        /// <summary>
        /// 改变时调用
        /// </summary>
        private void WhenMyValueChange()
        {
            _lastUpdateTime = DateTime.Now;
            OnMyValueChanged?.Invoke(this, null);
        }
        /// <summary>
        /// 获取时间间隔
        /// </summary>
        /// <returns></returns>
        private int GetTimeInterval()
        {
            return DateTime.Now.Subtract(_lastUpdateTime).Seconds;
        }
    }
}
